<template>
    <div class="page flex-row" v-loading="loading">
        <div class="left-container">
            <el-input
                    size="small"
                    placeholder="输入关键字进行过滤"
                    clearable
                    v-model="filterText">
            </el-input>
            <el-tree
                    ref="nodeTree"
                    class="filter-tree"
                    :data="nodeTree"
                    node-key="id"
                    :props="defaultProps"
                    :filter-node-method="filterNode">
                <div class="custom-tree-node flex-row flex-item"
                     @click.stop="nodeClick(node, data)"
                     :class="{'select-node': selectedFile.id === data.id}"
                     slot-scope="{ node, data }">
                    <high-light :value="node.label" :keyword="filterText"></high-light>
                </div>
            </el-tree>
        </div>
        <div class="right-container flex1">
            <div class="flex-row flex-item">
                <tz-filter @change="filterChange" :showNet="false" :filter-data="filterData">
                    <template v-slot:default="scope">
                        <el-input class="table-filter-item" :maxlength="20" size="small" clearable v-model="scope.data.fileName" placeholder="文件名称"></el-input>
                    </template>
                </tz-filter>
                <div class="flex1"></div>
                <el-button v-if="$auth['share_content_addfile']" @click="openCreate" size="mini" type="primary">新建文件夹</el-button>
                <upload v-if="$auth['share_content_uploadfile']" :id="selectedFile.id" style="margin-left: 10px" @finish="refresh">
                    <el-button size="mini" type="primary">上传文件</el-button>
                </upload>
            </div>
            <div v-if="$auth['share_content_uploadfile']" class="tip flex-row">
                <div class="flex1"></div>
                <div class="tip-text">上传格式不限，最大不能超过2GB</div>
            </div>
            <tz-table
                    :data="loadData"
                    row-key="id"
                    ref="fileTable"
                    size="mini">
                <el-table-column
                        prop="fileName"
                        show-overflow-tooltip
                        label="文件名">
                    <template slot-scope="scope">
                        <div class="file-name" @click="downloadFile(scope.row)">
                            <high-light :value="scope.row.fileName" :keyword="filterData.fileName"></high-light>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column
                        prop="fileName"
                        show-overflow-tooltip
                        label="预览">
                    <template slot-scope="scope">
                        <el-image v-if="scope.row.imgUrl"
                                style="width: 50px; height: 50px"
                                :preview-src-list="[scope.row.imgUrl]"
                                :src="scope.row.imgUrl"></el-image>
                        <a v-else-if="scope.row.videoUrl" :href="scope.row.videoUrl">{{scope.row.fileName}}</a>
                        <p v-else>没有预览</p>
                    </template>
                </el-table-column>
                <el-table-column
                        prop="fileType"
                        show-overflow-tooltip
                        label="文件类型">
                </el-table-column>
                <el-table-column
                        prop="size"
                        show-overflow-tooltip
                        label="文件大小"
                        :formatter="(row) => {
                            return row.size ? (((row.size || 0) / 1024).toFixed(2) + 'kb') : '-'
                        }"
                >
                </el-table-column>
                <el-table-column
                        prop="tag"
                        width="100px"
                        label="操作">
                    <template slot-scope="scope">
                        <el-button v-if="$auth['share_content_rename']" size="small" type="text" @click="editFile(scope.row)">重命名</el-button>
                        <el-button v-if="$auth['share_content_delete']" size="small" type="text" @click="deleteFile(scope.row)">删除</el-button>
                    </template>
                </el-table-column>
            </tz-table>
        </div>
        <el-dialog
                :title="dialogTitle"
                :visible.sync="dialogVisible"
                width="600px"
                style="text-align: left">
            <el-form ref="form" :model="fileFormInfo" label-width="80px">
                <el-form-item label="文件名称" prop="fileName">
                    <el-input size="small" maxLength="50" v-model="fileFormInfo.fileName" placeholder="请输入文件名"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button size="small" @click="dialogVisible = false">取 消</el-button>
                <el-button size="small" type="primary" @click="creatFolder">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import upload from '@/view/share/modules/upload';
import {apiBase} from '@/http/config';

export default {
  name: 'content-page',
  components: {
    upload
  },
  data() {
    return {
      loading: false,
      dialogVisible: false,
      dialogTitle: '',
      filterText: '',
      filterData: {
        fileName: '',
        fileType: ''
      },
      fileFormInfo: {
        fileName: ''
      },
      selectedFile: {
        fileName: '',
        fileType: '',
        id: 0
      },
      nodeTree: [{
        id: 0,
        fileName: '根目录',
        type: 'folder',
        children: []
      }],
      defaultProps: {
        label: 'fileName',
        children: 'children'
      },
      currentNet: {},
      imgTypes: ['jpg', 'jpeg', 'png', 'bmp', 'gif', 'tiff'],
      videoTypes: ['avi', 'mp4', 'wmv', 'flv', 'rmvb', 'rm']
    }
  },
  methods: {
    downloadFile(row) {
      if (row.fileType === 'folder') {
        this.selectedFile = {...row}
        this.refresh()
      } else {
        window.open(`${apiBase}/file/fileDownload?id=${row.id}`)
      }
    },
    filterChange(e) {
      console.log(e)
    },
    editFile(row) {
      this.dialogTitle = '修改文件名'
      this.dialogVisible = true
      this.fileFormInfo = { ...row }
    },
    deleteFile(row) {
      this.$confirm(`是否删除${row.fileName}?`).then(() => {
        this.$http.delete(`/file/deleteFile?id=${row.id}`).then(() => {
          this.refresh()
          this.queryFileTree()
        })
      }).catch(() => {
        this.$TZmessage.success('取消删除')
      })
    },
    openCreate() {
      this.dialogTitle = '新建文件夹'
      this.fileFormInfo.fileName = ''
      this.dialogVisible = true
    },
    creatFolder() {
      if (this.fileFormInfo.id) {
        this.$http.post('/file/modifiedFileName', this.fileFormInfo).then(() => {
          this.queryFileTree()
          this.refresh()
        }).finally(() => {
          this.dialogVisible = false
        })
      } else {
        this.$http.post('/file/saveFile', {
          fileName: this.fileFormInfo.fileName,
          fileType: 'folder',
          parentId: this.selectedFile.id
        }).then(() => {
          this.queryFileTree()
          this.refresh()
        }).finally(() => {
          this.dialogVisible = false
        })
      }
    },
    getUrl(item) {
      let url = ''
      if (this.imgTypes.includes(item.fileType.toLocaleLowerCase())) {
        // url = `${window.location.origin}/${process.env.NODE_ENV === 'development' ? 'api' : ''}/file/fileDownload?id=${item.id}`
        url = `${apiBase}/file/fileDownload?id=${item.id}`
        return {
          imgUrl: url
        }
      }
      if (this.videoTypes.includes(item.fileType.toLocaleLowerCase())) {
        url = `${window.location.origin}/${process.env.NODE_ENV === 'development' ? 'api' : ''}/file/fileDownload?id=${item.id}`
        return {
          videoUrl: url
        }
      }
      return {}
    },
    loadData(params) {
      return this.$http.get('/file/getChildrenFiles', {
        params: {
          ...params,
          id: this.selectedFile.id
        }
      }).then(res => {
        return {
          data: res.records.map(item => {
            return {
              ...item,
              ...this.getUrl(item)
            }
          }),
          total: res.total
        }
      })
    },
    queryFileTree() {
      this.$http.post('/file/getFilesTree', {
        fileType: 'folder'
      }).then(res => {
        this.nodeTree[0].children = res
      }).catch(err => {
        this.$TZmessage.error(err.msg || '获取目录失败')
      })
    },
    filterNode(value, data) {
      if (!value) {return true;}
      return data.fileName.indexOf(value) !== -1;
    },
    async nodeClick(node, data) {
      this.selectedFile = {...data}
      this.refresh()
      // await this.queryLocalNodeTree()
    },
    refresh() {
      this.$refs.fileTable.refresh()
    }
  },
  mounted() {
    this.queryFileTree()
  },
  watch: {
    filterText(val) {
      this.$refs.nodeTree.filter(val);
    }
  }
}
</script>

<style lang="scss" scoped>
    .page {
        .left-container {
            padding-right: 16px;
            border-right: 1px solid #DCDFE6;
            .filter-tree {
                padding-top: 10px;
            }
        }
        .right-container {
            padding: 0 16px;
            .tip-text {
                line-height: 30px;
                font-size: 12px;
                color: $color-warning;
            }
        }
        .custom-tree-node {
            width: 100%;
            height: 100%;
            padding-left: 5px;

        }
        .select-node {
            background: $primary;
            color: #ffffff;
        }
        .file-name {
            cursor: pointer;
            color: $primary;
        }
    }
</style>